﻿App.Localtion = function() {
    return {

        currentFormValues: {},

        getStore: function() {
            var store = new Ext.data.Store({
                autoLoad:true,
				baseParams : {start:0, limit:25},
				proxy: new Ext.data.HttpProxy({
					url : 'localtion/localtionList'
				}),
                remoteSort: false,
				reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'local_id',
					fields: [{
						name: 'local_id',
						type: 'string'
					},
					{
						name: 'local_code',
						allowBlank: false
					},
					{
						name: 'local_name',
						allowBlank: false
					},
					{
						name: 'local_area_code',
						allowBlank: false
					},
					{
						name: 'local_brief',
						allowBlank: false
					}]
				})
            });
            return store;
        },



        submit: function() {
            if (this.form.getForm().isValid()) {
                this.form.getForm().submit({
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                       var info = action.result.info;
                        if (action.result.success) {
                            this.store.reload();
                            if (action.result.method == "Create") {
                                this.form.getForm().reset();
                            } else {
                                this.dlg.hide();
                            }
                        }
                        Ext.Msg.alert('信息', info);
                    },
                    failure: function(form, action) {
                        var info = action.result.info;
	    				Ext.Msg.alert('提示', info);
                    }
                });
            }
        },


        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";

            var sm = new Ext.grid.CheckboxSelectionModel();
            this.grid = new Ext.grid.GridPanel({
            	anchor:'top 50%',
                loadMask: true,
                tbar: new Ext.PagingToolbar({ 
                	pageSize: 25 ,//分页必须加的参数.最好和store里面的limit保持一致
                	displayInfo: true,
                    store: this.store,
                    items:[
                    {
	                    text: '增加',
	                    scope: this,
	                    handler: this.add
	                },
	          //      {
	         //           text: '编辑',
	         //           scope: this,
	         //           handler: this.edit
	          //      },
	                {
	                    text: '删除',
	                    scope: this,
	                    handler: this.del
                },'-', new Ext.ux.form.SearchField({
                    store: this.store,
                    width: 110
                })]}),
                store: this.store,
                sm: sm,
                columns: [sm, 
                          new Ext.grid.RowNumberer(),
                {
                    header: "地点名称",
                    width: 60,
                    sortable: true,
                    dataIndex: 'local_name',
                    renderer: this.highLight
                },
                {
                    header: "地点代码",
                    width: 100,
                    sortable: true,
                    dataIndex: 'local_code',
                    renderer: this.highLight
                },
                {
                    header: "地点归属",
                    width: 100,
                    sortable: true,
                    dataIndex: 'local_area_code',
                    renderer: this.highLight
                },
                {
                    header: "地点简介",
                    width: 100,
                    sortable: true,
                    dataIndex: 'local_brief',
                    renderer: this.highLight
                }]
            });
            
            panel.add(this.grid);

        },
        getForm: function() {
            var form = new Ext.form.FormPanel({
				url:'localtion/save',
                labelAlign: 'left',
                buttonAlign: 'center',
                bodyStyle: 'padding:5px',
                frame: true,
                labelWidth: 80,
                defaultType: 'textfield',
                defaults: {
                    allowBlank: true,
                    anchor: '90%',
                    enableKeyEvents: true
                },
                items: [{
                    xtype: 'hidden',
                    name: 'id',
                    value: ''
                },{
                	 name: 'local_name',
                     fieldLabel: '地点名称'
                },
                {
                    name: 'local_code',
                    fieldLabel: '地点代码'
                },{
                    name: 'local_area_code',
                    fieldLabel: '地点归属'
                },
                {
                	name: 'local_brief',
                    fieldLabel: '地点简介'
                }],
                buttons: [{
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
            });
            return form;
        },
        getDialog: function() {
            var dlg = new Ext.Window({
                width: 400,
                height: 250,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.form],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.form.getForm().waitMsgTarget = fp.getEl();
                    },
                    show: function() {
//                        var f = this.form.getForm();
//                 //       f.findField("roleList").store.reload();
//                        f.setValues(this.currentFormValues);
//                        f.clearInvalid();
//                        if (this.currentFormValues.id) {
//                            Ext.get("pwdMsg").dom.innerHTML = "<span style='color:red;line-height:30px;'>*如果不修改密码请不要输入密码和确认密码</span>";
//                            f.findField("password").allowBlank = true;
//                            f.findField("confirmPassword").allowBlank = true;
//                        } else {
//                            f.findField("password").allowBlank = false;
//                            f.findField("confirmPassword").allowBlank = false;
//                            Ext.get("pwdMsg").dom.innerHTML = "<span style='color:red;'></span>";
//                        }
                    }
                }
            });
            return dlg;
        },
        highLight: function(value) {
        	var key = App.Localtion.grid.store.baseParams.query;
        	var v = value ? value.toString() : '';
        	if (Ext.isString(v) & Ext.isString(key)) {
        		if (key.length > 0) {
        			var re = new RegExp(key, "g");
        			return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
        		} else {
        			return v;
        		}
        	} else {
        		return v;
        	}
        },
        add: function() {
            Ext.apply(this.currentFormValues, {
                id: '',
                name: "",
                password: "",
                confirmPassword: "",
                roleList: ""
            });
            this.dlg.setTitle("增加地点");
            this.dlg.show();
        },

        edit: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                this.dlg.setTitle("编辑用户");
                var rec = this.grid.getSelectionModel().getSelected();
                var ml = [];
                for (var i = 0; i < rec.data.roles.length; i++) {
                    ml.push(rec.data.roles[i].staff_id);
                }
                Ext.apply(this.currentFormValues, {
                	staff_id: rec.data.id,
                    name: rec.data.name,
                    password: "",
                    confirmPassword: "",
                    roleList: ml.toString()
                });
                this.dlg.show();
            } else {
                Ext.Msg.alert('信息', '请选择要编辑的用户。');
            }
        },

        del: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                var recs = this.grid.getSelectionModel().getSelections();
                var ids = [];
                var titles = '';
                for (var i = 0; i < recs.length; i++) {
                    var data = recs[i].data;
                    ids.push(data.local_name);
                    titles += data.local_name + '<br>';
                }
                Ext.Msg.confirm('删除地点', '确定删除以下地点？<br><font color="red">' + titles + '</font>',
                function(btn) {
                    if (btn == 'yes') {
						Ext.Ajax.request({
							method:'post',
							url:'localtion/remove',
							params:{
								ids:ids.toString()
							},
							success: function(resp, opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								if(result.success=='true') {
									Ext.Msg.alert('信息', info);
                                    App.Localtion.store.reload();
								}else {
                                    Ext.Msg.alert('信息', info);
                                }
							},
							failure: function(resp,opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								Ext.Msg.alert('提示', info); 
							}
						});
                    }
                });
            } else {
                Ext.Msg.alert('信息', '请选择要删除的用户！');
            }
        },


        render: function(id) {
            if (!this.store) {
                this.store = this.getStore();
            };
            if (!this.form) {
                this.form = this.getForm();
            };
            if (!this.dlg) {
                this.dlg = this.getDialog();
            };
            this.createGrid(id);

        }
    };
} ();
